package com.hl.encrypt_descrypt;

import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;

import javax.net.ssl.SSLContext;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.*;
import java.security.cert.CertificateException;

/**
 * 1. 生成csr和key文件 (server.csr、server.key）
 * 2. xxxx.crt + server.key => xxxx.p12
 * 命令为：openssl pkcs12 -export -in xxxx.crt -inkey server.key -out xxxx.p12 -name haha -CAfile myCA.crt
 * 输入密码是a123456(可自定义)，要重复一次。可能会报错，但是不要紧，p12文件出来就行
 * 3. 然后将p12文件转换为jks文件
 * keytool -importkeystore -srckeystore haha.p12 -srcstoretype PKCS12 -srcstorepass a123456 -deststoretype JKS -destkeystore haha.jks -deststorepass b123456
 * 这样密码就是a123456，b123456
 *
 *
 * 客户端： https://blog.csdn.net/qq_36313856/article/details/111407772
 * 服务端写法：https://blog.csdn.net/qq_36313856/article/details/111407119
 * https://zhuanlan.zhihu.com/p/269817944
 */
public class Https {

    /**
     * @param certPath jks文件
     * @return
     */
    public CloseableHttpClient initHttpClient(String certPath) {
        CloseableHttpClient httpClient = null;
        try {
            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            //加载证书文件
            try (FileInputStream instream = new FileInputStream(certPath)) {
                //这里是storepass  b123456
                keyStore.load(instream, " b123456".toCharArray());
            }
            // 这里是源密码，a123456
            SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, "a123456".toCharArray()).build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
            httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
        } catch (KeyStoreException | IOException | NoSuchAlgorithmException | UnrecoverableKeyException |
                 CertificateException | KeyManagementException e) {
            e.printStackTrace();
        }
        return httpClient;
    }
}
